import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';

import '../common/flatPanel.dart';
import '../entry.dart';

class WordsPage extends StatefulWidget {
  final String title;

  WordsPage({Key key, this.title: Entry.Words}) : super(key: key);

  @override
  _WordsPageSate createState() {
    return _WordsPageSate();
  }
}

class _WordsPageSate extends State<WordsPage> {
  bool _addFlag = false;
  final _suggestions = <WordPair>[];
  final _saved = Set<WordPair>();
  final _biggerFont = TextStyle(fontSize: 18.0);

  void _prepareData() {
    _suggestions.addAll(generateWordPairs().take(10));
  }

  @override
  void initState() {
    super.initState();
    _prepareData();
  }

  Widget _buildRow(WordPair pair) {
    bool isSaved = _saved.contains(pair);
    return ListTile(
      title: Text(pair.asPascalCase, style: _biggerFont),
      trailing: Icon(isSaved ? Icons.favorite : Icons.favorite_border,
          color: isSaved ? Colors.red : null),
      onTap: () {
        setState(() {
          if (isSaved)
            _saved.remove(pair);
          else
            _saved.add(pair);
        });
      },
    );
  }

  // odd 奇数，even 偶数
  Widget _buildSuggestions() {
    return ListView.separated(
        padding: EdgeInsets.all(16),
        itemCount: _addFlag ? _suggestions.length + 10 : _suggestions.length,
        itemBuilder: (context, i) {
          // if (i.isOdd) return Divider();
          if (_addFlag) {
            _suggestions.addAll(generateWordPairs().take(10));
            _addFlag = false;
          }
          return _buildRow(_suggestions[i]);
        },
        separatorBuilder: (context, i) {
          return i % 2 == 0 ? Divider() : Divider(color: Colors.blue);
        });
  }

  void _addRows() {
    setState(() {
      _addFlag = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FlatPanel(
          child: _buildSuggestions(),
        ),
        floatingActionButton:
            FloatingActionButton(child: Icon(Icons.add), onPressed: _addRows));
  }
}
